<template>
  <div class="excel-container">
    <!-- 表格控制栏 -->
    <div class="control-bar">
      <button @click="addRow">
        <i class="fas fa-plus"></i> 添加行
      </button>
      <button @click="addColumn">
        <i class="fas fa-plus"></i> 添加列
      </button>
      <button @click="exportCSV">
        <i class="fas fa-file-export"></i> 导出CSV
      </button>
    </div>

    <!-- 表格容器 -->
    <div class="table-wrapper">
      <table>
        <thead>
          <tr>
            <th v-for="(col, colIndex) in columns" :key="colIndex">
              {{ getColumnName(colIndex) }}
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in data" :key="rowIndex">
            <td v-for="(cell, colIndex) in row" :key="colIndex">
              <input 
                type="text" 
                v-model="data[rowIndex][colIndex]"
                @keyup.enter="calculateFormula(rowIndex, colIndex)"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 公式栏 -->
    <div class="formula-bar">
      <input 
        type="text" 
        v-model="currentFormula"
        placeholder="输入公式（例如：=SUM(A1:B2)）"
        @keyup.enter="applyFormula"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { exportToCSV } from '../utils/excel-utils'

const columns = ref(10)
const rows = ref(20)
const data = reactive(Array.from({ length: rows.value }, () => 
  Array.from({ length: columns.value }, () => '')
))
const currentFormula = ref('')

const getColumnName = (index) => {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let name = ''
  do {
    name = letters[index % 26] + name
    index = Math.floor(index / 26) - 1
  } while (index >= 0)
  return name
}

const addRow = () => {
  data.push(Array.from({ length: columns.value }, () => ''))
}

const addColumn = () => {
  data.forEach(row => row.push(''))
  columns.value++
}

const calculateFormula = (row, col) => {
  const cellValue = data[row][col]
  if (cellValue.startsWith('=')) {
    try {
      const formula = cellValue.slice(1)
      data[row][col] = evalFormula(formula)
    } catch (error) {
      console.error('公式错误:', error)
    }
  }
}

const evalFormula = (formula) => {
  // 简单公式解析示例
  const sumMatch = formula.match(/^SUM\(([A-Z]+)(\d+):([A-Z]+)(\d+)\)$/i)
  if (sumMatch) {
    const startCol = sumMatch[1].toUpperCase()
    const startRow = parseInt(sumMatch[2]) - 1
    const endCol = sumMatch[3].toUpperCase()
    const endRow = parseInt(sumMatch[4]) - 1
    
    let sum = 0
    for (let r = startRow; r <= endRow; r++) {
      for (let c = columnToIndex(startCol); c <= columnToIndex(endCol); c++) {
        sum += parseFloat(data[r][c]) || 0
      }
    }
    return sum
  }
  return 'ERROR'
}

const columnToIndex = (colName) => {
  return colName.split('').reduce((acc, char) => 
    acc * 26 + char.toUpperCase().charCodeAt(0) - 64, 0) - 1
}

const applyFormula = () => {
  // 公式应用逻辑（示例）
  console.log('应用公式:', currentFormula.value)
  currentFormula.value = ''
}

const exportCSV = () => {
  exportToCSV(data)
}
</script>

<style scoped>
.excel-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.control-bar {
  padding: 10px;
  background: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  display: flex;
  gap: 10px;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

table {
  border-collapse: collapse;
  min-width: 100%;
}

th, td {
  border: 1px solid #dee2e6;
  padding: 8px;
  min-width: 120px;
  position: relative;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

input {
  width: 100%;
  border: none;
  outline: none;
  padding: 5px;
}

input:focus {
  background-color: #e9ecef;
}

.formula-bar {
  padding: 10px;
  border-top: 1px solid #dee2e6;
}

.formula-bar input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>